package com.qjdchina.sku.adaptor;

import com.qjdchina.commons.result.Result;
import com.qjdchina.commons.util.BeanUtil;
import com.qjdchina.sku.consts.WebConsts;
import com.qjdchina.sku.dao.mapper.ProductHisMapper;
import com.qjdchina.sku.dao.mapper.SkuProductMapper;
import com.qjdchina.sku.model.ProductHis;
import com.qjdchina.sku.model.SkuProduct;
import com.qjdchina.sku.service.enums.SkuResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * Created by fankiwu on 2016/12/1.
 */
@Service
public class ProductDaoAdaptor {

    @Autowired
    private SkuProductMapper skuProductMapper;

    @Autowired
    private ProductHisMapper productHisMapper;

    public static final Logger LOGGER = LoggerFactory.getLogger(ProductDaoAdaptor.class);

    /**
     *  更新产品信息
     * @param record
     * @return
     */
    public Result<Integer> addHistory(SkuProduct record, HttpSession httpSession){

        ProductHis productHis = skuProduct2ProductHis(record);
        // // TODO: 2016/12/1 换成session中的当前用户id 
        productHis.setOperateId((Integer) httpSession.getAttribute(WebConsts.USER_ID));

        // 插入历史表
        int insertCount = productHisMapper.insertSelective(productHis);

        if(0 == insertCount){
            LOGGER.warn("insert product his fail !");
            return new Result<Integer>(SkuResultCode.ADD_FAIL);
        }

        return new Result<Integer>(insertCount);
    }

    /**
     *
     * @param record
     * @return
     */
    private ProductHis skuProduct2ProductHis(SkuProduct record){
        ProductHis productHis = new ProductHis();
        BeanUtils.copyProperties(record, productHis);

        return productHis;
    }
}
